package com.exam.controller;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.exam.mapper.HandPaperMapper;
import com.exam.mapper.SelectMapper;
import com.exam.pojo.HandPaper;
import com.exam.pojo.Paper;
import com.exam.pojo.PaperQuestion;
import com.exam.pojo.Question;
import com.exam.service.HandPaperService;
import com.exam.service.PaperQuestionService;
import com.exam.service.PaperService;
import com.exam.service.QuestionService;
import com.exam.vo.AddExamByBankVo;
import com.exam.vo.AddExamByQuestionVo;
import com.exam.vo.QuestionVO;
import com.exam.vo.ResultData;
import com.exam.vo.examEnum.ResultCode;
import com.sun.org.apache.regexp.internal.RE;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;


/**
 * Created by 23115 on 2021/8/8 14:07
 */
@RestController
@RequestMapping(value = "/teacher")
@Slf4j
@Api(tags = "普通管理/教师相关的接口")
public class TeacherController {
    @Autowired
    private PaperService paperService;

    @Autowired
    public QuestionService questionService;

    @Autowired
    private PaperQuestionService paperQuestionService;
    @Autowired
    private HandPaperService handPaperService;
    @Autowired
    private SelectMapper selectMapper;

    @GetMapping("/getExam")
    @ApiOperation("查询考卷的信息")
    public ResultData getExamList(@RequestParam(required = false) String keyWord,
                                  Integer pageNo, Integer pageSize) {
        IPage<Paper> paperIPage = new Page<>(pageNo, pageSize);
        QueryWrapper<Paper> wrapper = new QueryWrapper<>();
        if (!Objects.equals(keyWord, null)) {
            wrapper.like("paperTitle", keyWord);
        }
        paperIPage = paperService.page(paperIPage, wrapper);
        Map<String, Object> map = new HashMap<>();
        List<Paper> papers = paperIPage.getRecords();
        map.put("total", paperIPage.getTotal());
        map.put("paperList", papers);
        return new ResultData(map);
    }

    @GetMapping("/handleExam")
    @ApiOperation("type=1(启用) 2(禁用) 3(删除) userIds(需要操作的考卷id)")
    public ResultData<String> handleExam(@RequestParam Integer type,@RequestParam String paperIds) {
        //转换成数组 需要操作的考卷的id数组
        String[] ids = paperIds.split(",");
        if (type == 1) {//启用
            for (String id : ids) {
                Paper paper = paperService.getById(Integer.parseInt(id));
                paper.setIsDelete(1);
                paperService.update(paper, new UpdateWrapper<Paper>().eq("id", Integer.parseInt(id)));
            }
            return new ResultData<>();
        } else if (type == 2) {//禁用
            for (String id : ids) {
                Paper paper = paperService.getById(Integer.parseInt(id));
                paper.setIsDelete(0);
                paperService.update(paper, new UpdateWrapper<Paper>().eq("id", Integer.parseInt(id)));
            }
            return new ResultData<>();
        } else if (type == 3) {//删除
            for (String id : ids) {
                paperService.removeById(Integer.parseInt(id));
                Map<String,Object> map=new HashMap<>();
                map.put("paper_id",id);
                paperQuestionService.removeByMap(map);
            }
            return new ResultData<>();
        } else return ResultData.error(ResultCode.BAD_REQUEST.getCode(), ResultCode.BAD_REQUEST.getMsg());
    }

    @PostMapping("/addExamByBank")
    @ApiOperation("根据题库添加考试")
    public ResultData<String> addExam1(@RequestBody AddExamByBankVo addExamByBankVo) {
        Paper paper = new Paper();
        paper.setIsDelete(addExamByBankVo.getStatus());
        paper.setDuration(addExamByBankVo.getExamDuration());
        if (addExamByBankVo.getEndTime() != null)
            paper.setEndTime(addExamByBankVo.getEndTime());
        if (addExamByBankVo.getStartTime() != null)
            paper.setStartTime(addExamByBankVo.getStartTime());
        paper.setPaperTitle(addExamByBankVo.getExamName());
        paper.setPassScore(addExamByBankVo.getPassScore());
        List<Paper> papers = paperService.list(new QueryWrapper<>());
        int id = 0;
        if (papers.size() != 0) {
            id = papers.get(papers.size() - 1).getId() + 1;
        }
        paper.setId(id);
        //构造考试中含有的题目信息
        PaperQuestion examQuestion = new PaperQuestion();
        examQuestion.setPaperId(id);
        //设置题目id字符串
        HashSet<Integer> set = new HashSet<>();
        String[] bankIds = addExamByBankVo.getBankIds().split(",");
        int singleNumber=addExamByBankVo.getSingleNumber();
        int multipleNumber=addExamByBankVo.getMultipleNumber();
        int judgeNumber=addExamByBankVo.getJudgeNumber();
        for (String bankId : bankIds) {
            List<Question> questions = questionService.list(new QueryWrapper<Question>().like("bank_id", Integer.parseInt(bankId)));
            for (Question question : questions) {
                if (question.getQuestionType() == 1) {//单选
                    for(;singleNumber>0;singleNumber--){
                        set.add(question.getId());
                        singleNumber--;
                        break;
                    }
                } else if (question.getQuestionType() == 2) {//多选
                    for(;multipleNumber>0;multipleNumber--){
                        set.add(question.getId());
                        multipleNumber--;
                        break;
                    }
                } else if (question.getQuestionType() == 3) {//判断
                    for(;judgeNumber>0;judgeNumber--){
                        set.add(question.getId());
                        judgeNumber--;
                        break;
                    }
                }

            }
        }
        String quIds = set.toString().substring(1, set.toString().length() - 1)
                .replaceAll(" ", "");
        examQuestion.setQuestionId(quIds);
        //设置每一题的分数
        String[] s = quIds.split(",");
        int totalScore = 0;
        StringBuilder sf = new StringBuilder();
        for (String s1 : s) {
            Question question = questionService.getById(Integer.parseInt(s1));
            if (question.getQuestionType() == 1) {//单选
                sf.append(addExamByBankVo.getSingleScore()).append(",");
                totalScore += addExamByBankVo.getSingleScore()*addExamByBankVo.getSingleNumber();
            } else if (question.getQuestionType() == 2) {//多选
                sf.append(addExamByBankVo.getMultipleScore()).append(",");
                totalScore += addExamByBankVo.getMultipleScore()*addExamByBankVo.getMultipleNumber();
            } else if (question.getQuestionType() == 3) {//判断
                sf.append(addExamByBankVo.getJudgeScore()).append(",");
                totalScore += addExamByBankVo.getJudgeScore()*addExamByBankVo.getJudgeNumber();
            }
        }
            examQuestion.setScore(sf.toString().substring(0, sf.toString().length() - 1));
            //设置总成绩
            paper.setTotalScore(totalScore);
            paperService.save(paper);
            paperQuestionService.save(examQuestion);
            return new ResultData<>();
        }

    @PostMapping("/addExamByQuestion")
    @ApiOperation("根据题目列表添加考卷")
    public ResultData<String> addExamByQuestion(@RequestBody AddExamByQuestionVo addExamByQuestionVo) {
        Paper paper = new Paper();
        paper.setTotalScore(addExamByQuestionVo.getTotalScore());
        paper.setPassScore(addExamByQuestionVo.getPassScore());
        if (addExamByQuestionVo.getEndTime() != null)
            paper.setEndTime(addExamByQuestionVo.getEndTime());
        if (addExamByQuestionVo.getStartTime() != null)
            paper.setStartTime(addExamByQuestionVo.getStartTime());
        paper.setPaperTitle(addExamByQuestionVo.getExamName());
        paper.setDuration(addExamByQuestionVo.getExamDuration());
        paper.setIsDelete(addExamByQuestionVo.getStatus());
        List<Paper> examList = paperService.list(new QueryWrapper<>());
        int id = 0;
        if (examList.size() != 0) {
            id = examList.get(examList.size() - 1).getId() + 1;
        }
        paper.setId(id);
        //设置考试的题目和分值信息
        PaperQuestion paperQuestion = new PaperQuestion();
        paperQuestion.setPaperId(id);
        paperQuestion.setScore(addExamByQuestionVo.getScores());
        paperQuestion.setQuestionId(addExamByQuestionVo.getQuestionIds());
        paperService.save(paper);
        paperQuestionService.save(paperQuestion);
        return new ResultData<>();
    }

    @PostMapping("/updateExam")
    @ApiOperation("修改考卷")
    public ResultData<String> updateExam(@RequestBody AddExamByQuestionVo addExamByQuestionVo) {
        Paper paper = new Paper();
        paper.setTotalScore(addExamByQuestionVo.getTotalScore());
        paper.setPassScore(addExamByQuestionVo.getPassScore());
        paper.setEndTime(addExamByQuestionVo.getEndTime());
        paper.setStartTime(addExamByQuestionVo.getStartTime());
        paper.setPaperTitle(addExamByQuestionVo.getExamName());
        paper.setDuration(addExamByQuestionVo.getExamDuration());
        paper.setIsDelete(addExamByQuestionVo.getStatus());
        paper.setId(addExamByQuestionVo.getExamId());
        //更新考试的题目和分值信息
        PaperQuestion examQuestion = new PaperQuestion();
        examQuestion.setPaperId(addExamByQuestionVo.getExamId());
        examQuestion.setScore(addExamByQuestionVo.getScores());
        examQuestion.setQuestionId(addExamByQuestionVo.getQuestionIds());
        paperService.update(paper, new UpdateWrapper<Paper>().eq("id", paper.getId()));
        paperQuestionService.update(examQuestion, new UpdateWrapper<PaperQuestion>().eq("paper_id", paper.getId()));
        return new ResultData<>();
    }

    @GetMapping("/getInfoById")
    @ApiOperation("根据考试id查询考试的信息和题目列表")
    public ResultData<List> getExamInfoById(@RequestParam Integer paperId) {
        AddExamByQuestionVo addExamByQuestionVo = new AddExamByQuestionVo();
        Paper paper = paperService.getOne(new QueryWrapper<Paper>().eq("id", paperId));
        addExamByQuestionVo.setExamDuration(paper.getDuration());
        addExamByQuestionVo.setExamId(paperId);
        addExamByQuestionVo.setExamName(paper.getPaperTitle());
        addExamByQuestionVo.setPassScore(paper.getPassScore());
        addExamByQuestionVo.setTotalScore(paper.getTotalScore());
        addExamByQuestionVo.setEndTime(paper.getEndTime());
        addExamByQuestionVo.setStartTime(paper.getStartTime());
        addExamByQuestionVo.setStatus(paper.getIsDelete());
        PaperQuestion paperQuestion = paperQuestionService.getOne(new QueryWrapper<PaperQuestion>().eq("paper_id", paperId));
        addExamByQuestionVo.setQuestionIds(paperQuestion.getQuestionId());
        addExamByQuestionVo.setScores(paperQuestion.getScore());
        List list=new ArrayList();
        list.add(addExamByQuestionVo);
        return new ResultData<>(list);
    }
    /**
     * 导出试卷信息
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportExam")
    public void excelExport(HttpServletResponse response, @RequestParam Integer paperId) throws IOException {
        AddExamByQuestionVo addExamByQuestionVo = new AddExamByQuestionVo();
        Paper paper = paperService.getOne(new QueryWrapper<Paper>().eq("id", paperId));
        addExamByQuestionVo.setExamDuration(paper.getDuration());
        addExamByQuestionVo.setExamId(paperId);
        addExamByQuestionVo.setExamName(paper.getPaperTitle());
        addExamByQuestionVo.setPassScore(paper.getPassScore());
        addExamByQuestionVo.setTotalScore(paper.getTotalScore());
        addExamByQuestionVo.setEndTime(paper.getEndTime());
        addExamByQuestionVo.setStartTime(paper.getStartTime());
        PaperQuestion paperQuestion = paperQuestionService.getOne(new QueryWrapper<PaperQuestion>().eq("paper_id", paperId));
        addExamByQuestionVo.setQuestionIds(paperQuestion.getQuestionId());
        String[] ids=paperQuestion.getQuestionId().split(",");
        List mapQuestion = new ArrayList<>();
        for (String id:ids) {
            //查询问题
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id",id);
            Question question = questionService.getBaseMapper().selectOne(queryWrapper);
            queryWrapper.clear();
            queryWrapper.eq("question_id",id);
            List selectList = selectMapper.selectList(queryWrapper);
            question.setQuestionSelect(selectList);
            QuestionVO questionVO = new QuestionVO(question);
            mapQuestion.add(questionVO);
        }
        JSONArray jsonArray = (JSONArray) JSONArray.toJSON(mapQuestion);
        addExamByQuestionVo.setQuestions(jsonArray.toJSONString());
        addExamByQuestionVo.setScores(paperQuestion.getScore());
        List list=new ArrayList();
        list.add(addExamByQuestionVo);
        String fileName = "考卷详情";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xls");
        ServletOutputStream out = response.getOutputStream();
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLS,true);
        Sheet sheet = new Sheet(1,0);
        sheet.setAutoWidth(Boolean.TRUE);
        writer.write(list,sheet);
        writer.finish();
        out.flush();
        response.getOutputStream().close();
        out.close();
    }
    @Autowired
    private HandPaperMapper handPaperMapper;
    @GetMapping("/getExamStatistics")
    @ApiOperation("成绩统计包括最高分，最低分，平均分，考试参加的人数")
    public ResultData<List> getExamStatistics(Integer pageNo, Integer pageSize) {
        Page<Map<String,Object>> pageInfo=new Page<>(pageNo,pageSize);
        IPage<Map> result=handPaperMapper.selectAHLN(pageInfo);
        List<Map> list=result.getRecords();
        System.out.println("总页数 = "+ result.getPages());
        return new ResultData<>(list);
    }
    @GetMapping("/getExamPass")
    @ApiOperation("考卷-及格人数")
    public ResultData<List> getExamPass(Integer pageNo, Integer pageSize) {
        Page<Map<String,Object>> pageInfo=new Page<>(pageNo,pageSize);
        IPage<Map> result=handPaperMapper.selectPass(pageInfo);
        List<Map> list=result.getRecords();
        list.forEach(System.out::println);
        System.out.println("总页数 = "+ result.getPages());
        return new ResultData<>(list);
    }
    @GetMapping("/getScore")
    @ApiOperation("考卷-姓名-得分")
    public ResultData<List> getScore(Integer pageNo, Integer pageSize) {
        Page<Map<String,Object>> pageInfo=new Page<>(pageNo,pageSize);
        IPage<Map> result=handPaperMapper.selectScore(pageInfo);
        List<Map> list=result.getRecords();
        System.out.println("总页数 = "+ result.getPages());
        return new ResultData<>(list);
    }
}
